package jh.activity

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jh.ios.forecast.R
import jh.adapter.PostAdapter
import jh.model.MTypeModel
import jh.model.Pic
import jh.model.UserModel
import jh.utils.HttpUtils
import jh.utils.NoDoubleClickListener
import jh.view.BxDialog
import kotlinx.android.synthetic.main.acitvity_personal_community.*
import kotlinx.android.synthetic.main.activity_post.*
import me.nereo.multi_image_selector.MultiImageSelector
import okhttp3.*
import org.apache.cordova.LoadingView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*

class PostActivity : BaseActivity(){


    private var titleText: EditText? = null
    private var contentText: EditText? = null
    //    private TextView lotteryStr;

    private var userModel: UserModel? = null
    private val lotterys = ArrayList<MTypeModel>()

    private val pickerData = ArrayList<String>()
    private var selectModel: MTypeModel? = null

    private var mSelectPath: ArrayList<String>? = null

    private var rightItem: LinearLayout? = null
    private var navigation_icon: ImageView? = null
    private var navigation_right: TextView? = null

    private var picList = ArrayList<Pic>()
    private var picPathStr = ArrayList<String>()  //保存图片压缩后的路径

    private var progressBar: ProgressBar? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_post
    }

    override fun initData(savedInstanceState: Bundle?) {   //bundle？可为空 不然闪崩
        userModel = UserModel.getUserInfo(this)
        uid = userModel!!.uid!!.toString() + ""
        loginToken = userModel!!.loginToken
        val pic = Pic()
        pic.picStr = "-1"  //-1作为标识用来加载加号按钮
        picList.add(pic)
//        getLotterys()
    }

    override fun initView() {

        backButton = find(R.id.back_buton)
        showBackButton()
        title = find(R.id.navigation_title)
        title.text = "发表内容"

        titleText = find(R.id.title)

        contentText = find(R.id.content)

        navigation_icon = findViewById(R.id.navigation_icon)
        navigation_icon!!.visibility = View.GONE

        navigation_right = findViewById(R.id.navigation_right)
        navigation_right!!.setTextColor(Color.parseColor("#80DCDCDC"))

        rightItem = find(R.id.navigation_item)
        rightItem!!.visibility = View.VISIBLE

        progressBar = find(R.id.progressBar)
//        //选择图片
//        find<ImageView>(R.id.img_select_pic).setOnClickListener {
//            pickImage()
//        }

        contentText!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                val str = s.toString()
                if (TextUtils.isEmpty(str)) {  //字符串判空
                    navigation_right!!.setTextColor(Color.parseColor("#80DCDCDC"))   //透明度50%
                    rightItem!!.setOnClickListener(null)
                } else {
                    navigation_right!!.setTextColor(Color.parseColor("#ffffff"))
                    rightItem!!.setOnClickListener(object : NoDoubleClickListener() {
                        override fun onNoDoubleClick(v: View?) {
                            rightClick()
                        }
                    })
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })
        //初始化recycleview
        initRecyclerView()

        mAdapter?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val pic = adapter.data[position] as Pic
            if (pic.picStr == "-1") {
                pickImage()
            } //加号按钮
            else {  //删除
                initDialog(position)
                if (!bxDialog?.isShowing!!) {  //防止重复弹出dialog
                    bxDialog?.show()
                }
            }
        }
    }

    private fun rightClick() {
        progressBar?.visibility=View.VISIBLE
        navigation_right!!.setTextColor(Color.parseColor("#80DCDCDC"))   //透明度50%
        rightItem!!.setOnClickListener(null)
        closeKeyBord()
        doAsync {
            postPic()
        }
    }

    private var mAdapter: PostAdapter? = null

    private fun initRecyclerView() {
        mAdapter = PostAdapter(R.layout.adapter_pic_post, picList)
        recycleView.apply {
            setHasFixedSize(true)
            layoutManager = GridLayoutManager(context, 3)
            adapter = mAdapter
        }
    }

//    override fun onClick(v: View) {
//        super.onClick(v)
//        if (v === rightItem) {
//            progressBar?.visibility=View.VISIBLE
//            navigation_right!!.setTextColor(Color.parseColor("#80DCDCDC"))   //透明度50%
//            rightItem!!.setOnClickListener(null)
//            closeKeyBord()
//            doAsync {
//                postPic()
//            }
//        }
//    }
lateinit var sb :StringBuilder
    //    上传图片
    private fun postPic() {
           sb=StringBuilder()
        if (picList.size==1&&picList[0].picStr=="-1"){
            submitAction("")
        }else{
            picPathStr.clear() //清空集合
            for (pic in 0 until  picList.size) {
                val onePicUrl = picList[pic].picStr
                if(onePicUrl!="-1"){  //-1说明是加载按钮
                    saveFile(BitmapFactory.decodeFile(onePicUrl), onePicUrl!!)
                    picPathStr.add(onePicUrl)  //保存图片压缩后的路径
                }
            }
//                uploadImage(onePicUrl)
            upload(picPathStr)  //挨张上传
        }
        navigation_right!!.setTextColor(Color.parseColor("#ffffff"))
        rightItem!!.setOnClickListener(this@PostActivity)
    }

    var flagPic=0 //从位标0的图片开始上传
    private fun upload(picPathStr: ArrayList<String>) {
            if (picPathStr.isEmpty()){
                return
            }
        if(flagPic<=picPathStr.size-1){
            uploadImage(picPathStr[flagPic])
        }else{
            flagPic=0
            //                val picSize= if(picList.size<=8){picList.size-1}else{x
//                    picList.size
//                }
                var sbStr=sb.toString()
//                Log.e("sdfasdfadf", "picFlag"+sbStr.split(",").size.toString()+"piclistsize"+picList.size.toString())
                if (sbStr.endsWith(",")) {sbStr=sbStr.substring(0,sbStr.length-1)}
                    if(sbStr.split(",").size==picPathStr.size){
                        submitAction(sbStr)
                    }
                Log.e("sdfasdfadf", sb.toString())
        }
    }

    private fun showToast(msg: String) {
        val toast = Toast.makeText(this, msg, Toast.LENGTH_LONG)
        toast.setGravity(GRAVITY_CENTER, 0, 0)
        toast.show()

    }

    private fun submitAction(img:String) {

        val url = "/api/communicationcircle/insertCommunication"

        val map = HashMap<String, String>()
        map.put("uid", uid)
        map.put("loginToken", loginToken)

        map.put("content", content.text.toString())
        map.put("imgs", img)

        HttpUtils.POST(url, map) { `object`, msg, e ->
            if (e == null) {
                if (msg == null) {
                    progressBar?.visibility=View.GONE
                    showToast("发表成功")
                    setResult(1000)
                    finish()
                }else{
                    navigation_right!!.setTextColor(Color.parseColor("#ffffff"))
                    rightItem!!.setOnClickListener(this@PostActivity)
                }
            }else{
//                navigation_right!!.setTextColor(Color.parseColor("#ffffff"))
//                rightItem!!.setOnClickListener(this@PostActivity)
            }
        }

    }


    //    private void showPickerView(){
    //        OptionsPickerView<String> mOptionsPickerView = new OptionsPickerView<>(this);
    //        // 设置数据
    //        mOptionsPickerView.setPicker(pickerData);
    //        mOptionsPickerView.setCancelTextColor(Color.rgb(255,0,0));
    //        mOptionsPickerView.setTitle("选择彩种");
    //        mOptionsPickerView.setSubmitTextColor(Color.rgb(0,255,0));
    //        mOptionsPickerView.setTitleColor(Color.parseColor("#888888"));
    //        mOptionsPickerView.setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
    //            @Override
    //            public void onOptionsSelect(int option1, int option2, int option3) {
    //                String sex = pickerData.get(option1);
    //                lotteryStr.setText(sex);
    //                selectModel = lotterys.get(option1);
    //            }
    //        });
    //        mOptionsPickerView.show();
    //    }


//    private fun getLotterys() {
//        val url = "/api/communicationcircle/getCategoryList"
//
//        val map = HashMap<String, String>()
//        map.put("loginToken", userModel!!.loginToken)
//
//        HttpUtils.POST(url, map) { `object`, msg, e ->
//            if (e == null) {
//                if (msg == null) {
//
//                    try {
//                        val jsonArray = `object`.getJSONArray("data")
//                        val builder = GsonBuilder()
//                        val gson = builder.create()
//                        val list = gson.fromJson<List<MTypeModel>>(jsonArray.toString(), object : TypeToken<List<MTypeModel>>() {
//
//                        }.type)
//                        lotterys.addAll(list)
//
//                        for (model in list) {
//                            pickerData.add(model.lotteryCategoryName)
//                        }
//                        if (list.size > 0) {
//                            selectModel = list[0]
//                            //                                lotteryStr.setText(list.get(0).getLotteryCategoryName());
//                        }
//
//                    } catch (e1: JSONException) {
//                        e1.printStackTrace()
//                    }
//
//                }
//            }
//        }
//    }

    private fun pickImage() {
        val maxNum = 9   //最大九张
        val selector = MultiImageSelector.create()
        selector.showCamera(true)
        selector.count(maxNum)
        selector.multi()
        selector.origin(mSelectPath)
        selector.start(this@PostActivity, REQUEST_IMAGE)
    }

    /**
     * 6.0+动态申请权限
     * 接收权限申请结果
     *
     * requestCode 请求码
     *
     * permissions 权限申请数组
     *
     * grantResults 申请之后的结果数组
     *
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    //权限申请成功
                    toast("授权成功")
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data!!.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT)
                if (mSelectPath == null) return
                //先清除掉集合中的加号按钮 后面再添加加号按钮
                picList.forEachIndexed { index, pic ->
                    if (pic.picStr == "-1") picList.remove(pic)
                }
                labelA@ for (p in mSelectPath!!) {
                    //遍历mSelectPath，如果picStr里已经有了重复数据，不添加进picStr。
                    labelB@ for (m in picList) {
                        if (p == m.picStr) {
                            continue@labelA     //直接返回labelA进行下一次循环，不执行后面代码
                        }
                    }

                    val pic = Pic()
                    pic.picStr = p
                    picList.add(pic)
                }
                if (picList.size <= 8) {
                    val pic = Pic()
                    pic.picStr = "-1"  //-1作为标识用来加载加号按钮
                    picList.add(pic)
                }
                recycleView.adapter?.notifyDataSetChanged()
            }
        }
    }

    companion object {
        private val GRAVITY_CENTER = Gravity.CENTER_VERTICAL or Gravity.CENTER_HORIZONTAL
        private val REQUEST_IMAGE = 2
    }

    private var bxDialog: BxDialog? = null
    private fun initDialog(pos: Int) {
        if (null == bxDialog) {
            bxDialog = BxDialog(this, R.style.myDialog).loadLayout(R.layout.dialog_layout)
            bxDialog?.setGCCanceledOnTouchOutside(true)
        }
        //是
        bxDialog?.setOnClickListener(R.id.btn_sure, {
            bxDialog?.dismiss()
            picList.removeAt(pos)
            val pic = Pic()
            pic.picStr = "-1"
            if (!picList.contains(pic)) {
                picList.add(pic)
            }
            mAdapter?.notifyDataSetChanged()
        })
        //否
        bxDialog?.setOnClickListener(R.id.btn_cancel, {
            bxDialog?.dismiss()

        })

//        bxDialog?.setOnKeyListener(DialogUtils.keylistener)  //禁用物理返回键关闭dialog

    }

    /**
     * 图片质量压缩并保存
     * @param bm
     * @param fileName
     * @throws Exception
     */
    fun saveFile(bm: Bitmap, fileName: String) {
        try {
            val dirFile = File(fileName)
            //检测图片是否存在
            if (dirFile.exists()) {
                dirFile.delete()  //删除原图片
            }
            val myCaptureFile = File(fileName)
            var bos: BufferedOutputStream? = null
            bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
            //100表示不进行压缩，70表示压缩率为30%,质量压缩 最低只能30了，再低原图被损坏
            bm.compress(Bitmap.CompressFormat.JPEG, 30, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    var domain = "http://47.244.180.213:8200"
    var url = "/api/userinfo/uploadPhoto"
    var uid = ""
    var loginToken = ""


    /**
     * 上传图片
     * @param url
     * @param imagePath 图片路径
     * @return 新图片的路径
     * @throws IOException
     * @throws JSONException
     */
    @Throws(IOException::class, JSONException::class)
    fun uploadImage(imagePath: String?) {
        var returnImg = ""
        val file = File(imagePath)
        val MEDIA_TYPE_PNG = MediaType.parse("image/png")
        val filebody = MultipartBody.create(MEDIA_TYPE_PNG, file)
        val multiBuilder = MultipartBody.Builder()
        //这里是 封装上传图片参数
        multiBuilder.addFormDataPart("file", file.name, filebody)
        //参数以添加header方式将参数封装，否则上传参数为空
        // 设置请求体
        multiBuilder.setType(MultipartBody.FORM)
        //这里是 封装上传图片参数
//        multiBuilder.addFormDataPart("name", file.name, filebody)
        // 封装请求参数,这里最重要
        val params = HashMap<String, String>()
        //        params.put("client","Android");
        params.put("uid", uid)
        params.put("loginToken", loginToken)
        params.put("fileName", "avatarName.jpg")
        //参数以添加header方式将参数封装，否则上传参数为空
        if (!params.isEmpty()) {
            for (key in params.keys) {
                multiBuilder.addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                        RequestBody.create(null, params[key]))
            }
        }
        val multiBody = multiBuilder.build()
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(domain + url).post(multiBody).build()
        val call = okHttpClient.newCall(request)



        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                //请求失败的处理
                Log.e("sdfasdfadf", "失败请求")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                var jsonObject: JSONObject? = null
                try {
                    jsonObject = JSONObject(response.body()!!.string())
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                returnImg = jsonObject!!.optString("data")
                sb.append(returnImg)
                sb.append(",")
                flagPic++
                upload(picPathStr)  //挨张上传
//                val picSize= if(picList.size<=8){picList.size-1}else{
//                    picList.size
//                }
//                var sbStr=sb.toString()
////                Log.e("sdfasdfadf", "picFlag"+sbStr.split(",").size.toString()+"piclistsize"+picList.size.toString())
//                if (sbStr.endsWith(",")) {sbStr=sbStr.substring(0,sbStr.length-1)}
//                    if(sbStr.split(",").size==picSize){
//                        submitAction(sbStr)
//                    }
//                Log.e("sdfasdfadf", sb.toString())

            }
        })
    }

    /**
     * 关闭软键盘
     */
    private fun closeKeyBord() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(content.windowToken, 0)
    }

}
